"""
File:03_SSH登陆模块.py
Author:Tcyw
Date:2020-05-04
Connect:741047561@qq.com
Description:

"""
import logging

import pexpect


# # 1.通过pexpect执行指令(无交互)
# # 执行命令并返回命令执行结果和状态码(0:代表执行成功，其他代表执行失败)
# (command_output, exitstatus) = pexpect.run('hostname', withexitstatus=1) # withexitstatus命令执行结束时返回一个命令执行的状态码
# command_output = command_output.decode('utf-8')
# print(command_output)
# if exitstatus == 0:
#     print('命令执行成功', command_output)
# else:
#     print('命令执行失败', command_output)

# # 2. 通过pexpect执行指令(有交互)
# command = 'ssh -p22 root@172.25.254.15'
# # spawn开启一个子进程处理交互式操作
# child = pexpect.spawn(command, timeout=30)
# # 匹配交互信息，返回的是匹配到信息的索引
# match_index = child.expect(['continue connecting (yes/no)?', 'password:'])
# print(match_index)
# print(type(match_index))
# # 如果索引是0， 代表第一次连接， 先输入yes， 再输入密码
# if match_index == 0:
#     print('第一次登陆')
#     child.sendline('yes\n')
#     child.expect(['password:', pexpect.EOF, pexpect.TIMEOUT])
#     child.sendline('westos\n')
# elif match_index == 1:
#     print('非第一次登陆')
#     child.sendline('westos\n')
#
# login_index = child.expect(['root', '$', pexpect.EOF, pexpect.TIMEOUT])
# print(login_index)
# if login_index == 0:
#     print('超级用户登陆')
#
# elif login_index == 1:
#     print('普通用户登陆')

#
# def login_ssh_password(user, host, password, port=22):
#     command = 'ssh -p%s %s@%s' %(port, user, host)
#     # spawn开启一个子进程处理交互式操作
#     child = pexpect.spawn(command, timeout=20)
#     # 匹配交互信息, 返回的是匹配到信息的索引
#     match_index = child.expect(['continue connecting (yes/no)?', 'password:'])
#     print(match_index)
#     # 如果索引是0， 代表第一次连接， 先输入yes， 再输入密码
#     if match_index == 0:
#         print("第一次登录")
#         child.sendline('yes\n')
#         child.expect(['password:'])
#         child.sendline(password+'\n')
#     # 如果索引是1， 代表不是第一次登录， 则直接输入密码即可。
#     elif match_index == 1:
#         print("非第一次登录")
#         child.sendline(password+'\n')
#
#     login_index = child.expect(['#', pexpect.EOF, pexpect.TIMEOUT])
#     print(login_index)
#     if login_index == 0:
#         print("超级登录成功")
#         # 进入远程服务器的命令行
#         child.interact()
#     elif login_index == 1:
#         print("登录失败: Logout")
#     elif login_index == 2:
#         print("登录失败: 超时")

def login_ssh_key(hostname, keyfile, username, port=22):
    """
          用于实现pexpect实现ssh的自动化密钥管理
          """
    print("ssh -i %s -p%s %s@%s" % (keyfile, port, username, hostname))
    if hostname and keyfile and username and port:
        ssh = pexpect.spawn("ssh -i %s -p%s %s@%s" % (keyfile, port,
                                                      username, hostname))
        status_code = ssh.expect(['root', pexpect.TIMEOUT, 'continue connecting(yes / no)?'], timeout=50)
        print(status_code)
        if status_code == 2:
            ssh.sendline('yes\n')
        # index = ssh.expect(["#", pexpect.EOF, pexpect.TIMEOUT])
        if status_code == 0:
            print("logging in as root!")
            logging.info("logging in as root!")
            # 进入交互式环境
            ssh.interact()
        # elif status_code == 1:
        #     print("logging process exit!")
        #     logging.error("logging process exit!")
        elif status_code == 1:
            print("logging timeout exit!")
            logging.error("logging timeout exit!")
    else:
        print("Paramiko error!")
        logging.error("Parameter error!")

if __name__ == '__main__':
    login_ssh_key(hostname='172.25.254.15', keyfile='/root/.ssh/id_rsa', username='root')
